﻿using System.Net.Sockets;
using System.Net;
public class ChattingServer
{
    public static Socket socket;
    public static List<ClinetInfo> clients = new List<ClinetInfo>();
    public class ClinetInfo
    {
        public Socket socket;
        public byte[] buffer = new byte[1024];
        public ClinetInfo(Socket socket)
        {
            this.socket = socket;
        }
    }

    public static void Main(string[] argv)
    {
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Any, 10010));
            socket.Listen(0);
            socket.BeginAccept(AcceptCallback, socket);
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    public static void AcceptCallback(IAsyncResult result)
    {
        try
        {
            Socket socket = (Socket)result.AsyncState;
            Socket client = socket.EndAccept(result);
            ClinetInfo info = new ClinetInfo(client);
            clients.Add(info);
            client.BeginReceive(info.buffer, 0, 1024, 0, ReceiveCallback, info);
            socket.BeginAccept(AcceptCallback, socket);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    public static void ReceiveCallback(IAsyncResult result)
    {
        try
        {
            ClinetInfo info = (ClinetInfo)result.AsyncState;
            int count = info.socket.EndReceive(result);

            foreach (var c in clients)
                c.socket.Send(info.buffer, 0, count, 0);

            info.socket.BeginReceive(info.buffer, 0, 1024, 0, ReceiveCallback, info);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
}